require 'digit2word/dict'
require 'digit2word/convert'

module Control
  class ConsoleController < BaseController

    def convert
      @output = ""
      if params[:number].strip.present?
        matched_words = convert_number(params[:number])
        if matched_words.present?
          @output << "> #{matched_words.size} words matched!<br />"
          @output << matched_words.map{|x| "> &nbsp;&nbsp;&nbsp;#{x}"}.join('<br />')
          record_matching_activity(params[:number], matched_words)
        else
          @output << "> No word matched!"
        end
      else
        @output << "> Please input number!"
      end
    end

    private
    def convert_number(number)
      dicts = current_user.dicts.pluck(:name)
      word_pattern = Regexp.new(dicts.map{|x| Regexp.escape(x) }.join('|'), true)
      Digit2word::Convert.new.send(:convert_number_with_pattern, number, word_pattern)
    end

    def record_matching_activity(number, matched_words)
      current_user.results.create(number: number, matched_words: matched_words)
    end

  end
end
